<template>
  <div class="screen-capture-wrapper">
    <!-- 截屏触发按钮 -->
    <SvgIcons 
      iconClass="icon_caijian" 
      class="cur-pointer hoverClass mar-r-15" 
      @click="startCapture"
      title="截屏裁剪"
    />
    
    <!-- 截屏遮罩层 -->
    <div v-if="isCapturing" class="capture-overlay" @mousedown="handleOverlayMouseDown">
      <!-- 选择区域 -->
      <div 
        v-if="selection.width > 0 && selection.height > 0"
        class="selection-area" 
        :style="selectionStyle"
        @mousedown="handleSelectionMouseDown"
      >
        <div class="size-info">
          {{ selection.width }} × {{ selection.height }}
        </div>
        
        <!-- 控制点 -->
        <div 
          v-for="point in controlPoints" 
          :key="point.position"
          class="control-point"
          :class="point.position"
          :style="point.style"
          @mousedown.stop="startResize($event, point.position)"
        ></div>
      </div>
      
      <!-- 操作工具栏 -->
      <div 
        v-if="selection.width > 10 && selection.height > 10" 
        class="toolbar" 
        :style="toolbarStyle"
        @mousedown.stop
      >
        <el-button size="mini" type="success" @click.stop="confirmCapture">确认</el-button>
        <el-button size="mini" type="danger" @click.stop="cancelCapture">取消</el-button>
        <el-button size="mini" @click.stop="resetSelection">重选</el-button>
      </div>
    </div>
  </div>
</template>

<script>
// 先检查是否安装了 html2canvas
let html2canvas = null
try {
  html2canvas = require('html2canvas')
} catch (error) {
  console.warn('html2canvas 未安装，请运行: npm install html2canvas')
}

export default {
  name: 'ScreenCapture',

  components: {
    SvgIcons: () => import('@/components/SvgIcons')
  },
  
  props: {
    // 截图质量 (0-1)
    quality: {
      type: Number,
      default: 1
    },
    // 截图格式
    format: {
      type: String,
      default: 'png'
    }
  },
  
  data() {
    return {
      isCapturing: false,
      isSelecting: false,
      isDragging: false,
      isResizing: false,
      
      selection: {
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        startX: 0,
        startY: 0
      },
      
      resizeInfo: {
        direction: '',
        startX: 0,
        startY: 0,
        startSelection: null
      }
    }
  },
  
  computed: {
    selectionStyle() {
      return {
        left: this.selection.x + 'px',
        top: this.selection.y + 'px',
        width: this.selection.width + 'px',
        height: this.selection.height + 'px'
      }
    },
    
    toolbarStyle() {
      const toolbarX = this.selection.x + this.selection.width + 10
      const toolbarY = this.selection.y
      
      // 确保工具栏在可视区域内
      const viewportWidth = window.innerWidth
      const viewportHeight = window.innerHeight
      
      let adjustedX = toolbarX
      let adjustedY = toolbarY
      
      if (toolbarX + 200 > viewportWidth) {
        adjustedX = this.selection.x - 210
      }
      
      if (toolbarY + 100 > viewportHeight) {
        adjustedY = this.selection.y - 110
      }
      
      return {
        left: adjustedX + 'px',
        top: adjustedY + 'px'
      }
    },
    
    controlPoints() {
      const points = [
        { position: 'top-left', x: -4, y: -4 },
        { position: 'top-right', x: this.selection.width - 4, y: -4 },
        { position: 'bottom-left', x: -4, y: this.selection.height - 4 },
        { position: 'bottom-right', x: this.selection.width - 4, y: this.selection.height - 4 }
      ]
      
      return points.map(point => ({
        ...point,
        style: {
          left: point.x + 'px',
          top: point.y + 'px'
        }
      }))
    }
  },
  
  methods: {
    // 开始截屏
    startCapture() {
      if (!html2canvas) {
        this.$message.error('截屏功能依赖 html2canvas，请先安装: npm install html2canvas')
        return
      }
      
      this.isCapturing = true
      this.setupEventListeners()
      this.$emit('capture-start')
    },
    
    // 设置事件监听
    setupEventListeners() {
      document.addEventListener('mousemove', this.handleMouseMove)
      document.addEventListener('mouseup', this.handleMouseUp)
      document.addEventListener('keydown', this.handleKeyDown)
    },
    
    // 移除事件监听
    removeEventListeners() {
      document.removeEventListener('mousemove', this.handleMouseMove)
      document.removeEventListener('mouseup', this.handleMouseUp)
      document.removeEventListener('keydown', this.handleKeyDown)
    },
    
    // 遮罩层鼠标按下事件
    handleOverlayMouseDown(e) {
      if (!this.isCapturing) return
      
      // 检查是否点击了工具栏
      if (e.target.closest('.toolbar')) {
        return
      }
      
      // 检查是否点击了控制点
      if (e.target.closest('.control-point')) {
        return
      }
      
      const inSelection = this.isInSelectionArea(e.clientX, e.clientY)
      
      if (inSelection) {
        // 拖拽移动
        this.startDrag(e)
      } else {
        // 开始新选择
        this.startNewSelection(e)
      }
    },
    
    // 选择区域鼠标按下事件
    handleSelectionMouseDown(e) {
      if (!this.isCapturing) return
      
      // 阻止事件冒泡到遮罩层
      e.stopPropagation()
      
      const inControlPoint = this.isInControlPoint(e.clientX, e.clientY)
      
      if (!inControlPoint) {
        // 拖拽移动
        this.startDrag(e)
      }
    },
    
    // 开始选择区域
    startNewSelection(e) {
      this.isSelecting = true
      this.selection.startX = e.clientX
      this.selection.startY = e.clientY
      this.selection.x = e.clientX
      this.selection.y = e.clientY
      this.selection.width = 0
      this.selection.height = 0
    },
    
    // 开始拖拽
    startDrag(e) {
      this.isDragging = true
      this.resizeInfo.startX = e.clientX - this.selection.x
      this.resizeInfo.startY = e.clientY - this.selection.y
    },
    
    // 开始调整大小
    startResize(e, direction) {
      e.stopPropagation()
      this.isResizing = true
      this.resizeInfo.direction = direction
      this.resizeInfo.startX = e.clientX
      this.resizeInfo.startY = e.clientY
      this.resizeInfo.startSelection = { ...this.selection }
    },
    
    // 鼠标移动事件
    handleMouseMove(e) {
      if (!this.isCapturing) return
      
      if (this.isSelecting) {
        this.updateSelection(e)
      } else if (this.isDragging) {
        this.moveSelection(e)
      } else if (this.isResizing) {
        this.resizeSelection(e)
      }
    },
    
    // 更新选择区域
    updateSelection(e) {
      const minX = Math.min(this.selection.startX, e.clientX)
      const minY = Math.min(this.selection.startY, e.clientY)
      const maxX = Math.max(this.selection.startX, e.clientX)
      const maxY = Math.max(this.selection.startY, e.clientY)
      
      this.selection.x = minX
      this.selection.y = minY
      this.selection.width = maxX - minX
      this.selection.height = maxY - minY
    },
    
    // 移动选择区域
    moveSelection(e) {
      this.selection.x = e.clientX - this.resizeInfo.startX
      this.selection.y = e.clientY - this.resizeInfo.startY
      this.constrainToViewport()
    },
    
    // 调整选择区域大小
    resizeSelection(e) {
      const deltaX = e.clientX - this.resizeInfo.startX
      const deltaY = e.clientY - this.resizeInfo.startY
      const start = this.resizeInfo.startSelection
      
      switch (this.resizeInfo.direction) {
        case 'top-left':
          this.selection.x = start.x + deltaX
          this.selection.y = start.y + deltaY
          this.selection.width = start.width - deltaX
          this.selection.height = start.height - deltaY
          break
        case 'top-right':
          this.selection.y = start.y + deltaY
          this.selection.width = start.width + deltaX
          this.selection.height = start.height - deltaY
          break
        case 'bottom-left':
          this.selection.x = start.x + deltaX
          this.selection.width = start.width - deltaX
          this.selection.height = start.height + deltaY
          break
        case 'bottom-right':
          this.selection.width = start.width + deltaX
          this.selection.height = start.height + deltaY
          break
      }
      
      // 确保最小尺寸
      if (this.selection.width < 10) this.selection.width = 10
      if (this.selection.height < 10) this.selection.height = 10
      
      this.constrainToViewport()
    },
    
    // 限制在可视区域内
    constrainToViewport() {
      const viewportWidth = window.innerWidth
      const viewportHeight = window.innerHeight
      
      this.selection.x = Math.max(0, Math.min(this.selection.x, viewportWidth - this.selection.width))
      this.selection.y = Math.max(0, Math.min(this.selection.y, viewportHeight - this.selection.height))
    },
    
    // 鼠标释放事件
    handleMouseUp() {
      this.isSelecting = false
      this.isDragging = false
      this.isResizing = false
    },
    
    // 键盘事件
    handleKeyDown(e) {
      if (e.key === 'Escape') {
        this.cancelCapture()
      } else if (e.key === 'Enter' && this.selection.width > 10) {
        this.confirmCapture()
      }
    },
    
    // 确认截屏
    async confirmCapture() {
        if (!html2canvas) {
            this.$message.error('html2canvas 未安装')
            return
        }
        
        if (this.selection.width < 10 || this.selection.height < 10) {
            this.$message.warning('请选择更大的区域')
            return
        }
        
        try {
            const canvas = await html2canvas(document.body, {
            x: this.selection.x,
            y: this.selection.y,
            width: this.selection.width,
            height: this.selection.height,
            scale: 1,
            useCORS: false, // 禁用 CORS
            allowTaint: false, // 不允许污染画布
            backgroundColor: null,
            ignoreElements: (element) => {
                // 忽略图片元素
                if (element.tagName === 'IMG') {
                const src = element.src || '';
                // 如果是跨域图片，忽略它
                if (src && !src.startsWith('data:') && !src.startsWith('blob:')) {
                    try {
                    const url = new URL(src, window.location.origin);
                    if (url.origin !== window.location.origin) {
                        return true; // 忽略跨域图片
                    }
                    } catch (e) {
                    // 如果 URL 解析失败，忽略该图片
                    return true;
                    }
                }
                }
                return false;
            },
            onclone: (clonedDoc) => {
                // 在克隆的文档中移除跨域图片
                const images = clonedDoc.querySelectorAll('img');
                images.forEach(img => {
                const src = img.src || '';
                if (src && !src.startsWith('data:') && !src.startsWith('blob:')) {
                    try {
                    const url = new URL(src, window.location.origin);
                    if (url.origin !== window.location.origin) {
                        img.remove(); // 移除跨域图片
                    }
                    } catch (e) {
                    img.remove(); // 移除无法解析的图片
                    }
                }
                });
            }
            })
            
            const imageData = canvas.toDataURL(`image/${this.format}`, this.quality)
            this.$emit('capture-success', imageData)
            this.cleanup()
            
        } catch (error) {
            console.error('截屏失败:', error)
            this.$message.error('截屏失败，请重试')
            this.$emit('capture-error', error)
        }
    },
    
    // 取消截屏
    cancelCapture() {
      this.cleanup()
      this.$emit('capture-cancel')
    },
    
    // 重置选择
    resetSelection() {
      this.selection = {
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        startX: 0,
        startY: 0
      }
      this.isSelecting = false
      this.isDragging = false
      this.isResizing = false
    },
    
    // 清理资源
    cleanup() {
      this.isCapturing = false
      this.removeEventListeners()
      this.resetSelection()
    },
    
    // 检查是否在选择区域内
    isInSelectionArea(x, y) {
      return x >= this.selection.x && 
             x <= this.selection.x + this.selection.width && 
             y >= this.selection.y && 
             y <= this.selection.y + this.selection.height
    },
    
    // 检查是否在控制点内
    isInControlPoint(x, y) {
      return this.controlPoints.some(point => {
        const pointX = this.selection.x + parseInt(point.style.left)
        const pointY = this.selection.y + parseInt(point.style.top)
        return Math.abs(x - pointX) <= 6 && Math.abs(y - pointY) <= 6
      })
    }
  },
  
  beforeDestroy() {
    this.removeEventListeners()
  }
}
</script>

<style lang="scss" scoped>
.screen-capture-wrapper {
  display: inline-block;
}

.capture-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.3);
  z-index: 9998;
  cursor: crosshair;
}

.selection-area {
  position: absolute;
  border: 2px solid #409EFF;
  background: rgba(64, 158, 255, 0.1);
  box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.3);
  cursor: move;
  
  .size-info {
    position: absolute;
    bottom: -25px;
    left: 0;
    background: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 2px 6px;
    border-radius: 3px;
    font-size: 12px;
    white-space: nowrap;
  }
  
  .control-point {
    position: absolute;
    width: 8px;
    height: 8px;
    background: #409EFF;
    border: 2px solid white;
    border-radius: 50%;
    box-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
    
    &.top-left {
      cursor: nw-resize;
    }
    &.top-right {
      cursor: ne-resize;
    }
    &.bottom-left {
      cursor: sw-resize;
    }
    &.bottom-right {
      cursor: se-resize;
    }
  }
}

.toolbar {
  position: absolute;
  background: white;
  padding: 8px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 9999;
  
  .el-button {
    margin: 0 2px;
  }
}
</style>